package cn.itboys.commons;

import cn.itboys.commons.utils.encryption.Digests;
import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

/**
 * 生成签名
 * @author: huml
 * @createTime: 2021/8/4
 */
public class SignUtil {

    public static void main(String[] args){
        //{"title":"我是接口给的标题",
        // "patientName":"患者姓名",
        // "patientAge":"50",
        // "department":"科室",
        // "content":"内容",
        // "appKey":"woshiappkey",
        // "timestamp":"162692124"}
        Map<String, Object> params = new TreeMap<>(new MapKeyComparator());
        params.put("title", "我是接口给的标题");
        params.put("patientName", "患者姓名");
        params.put("patientAge", 50);
        params.put("department", "科室");
        params.put("timestamp", "162692124");
        params.put("appKey", "woshiappkey");
        System.out.println(makeSign(params, "woshiappsecret"));
    }

    public static String makeSign(Map<String, Object> params, String secret){
        System.out.println("params = " + JSON.toJSONString(params));
        //遍历params, 得到key1value1key2value2的字符串
        StringBuilder sb = new StringBuilder();
        //拼接参数
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(entry.getKey());
            sb.append("=");
            sb.append(entry.getValue().toString());
        }
        //加上secret
        sb.append("&key="  + secret);
        //appKey=woshiappkey&department=%E7%A7%91%E5%AE%A4&patientAge=50&patientName=%E6%82%A3%E8%80%85%E5%A7%93%E5%90%8D&timestamp=162692124&title=%E6%88%91%E6%98%AF%E6%8E%A5%E5%8F%A3%E7%BB%99%E7%9A%84%E6%A0%87%E9%A2%98&key=woshiappsecret
        System.out.println("sign str = " + sb.toString());

        return DigestUtils.md5Hex(sb.toString()).toUpperCase();
    }

}

class MapKeyComparator implements Comparator<String> {

    @Override
    public int compare(String str1, String str2) {

        return str1.compareTo(str2);
    }
}
